<?php
//最后登录时间lasttime还没做，
//即上一次退出的时间：setcookie('lasttime',time(),time()+60,'/');

include_once 'D:/dingjiangbbs/common/home.php';
session_start();

//屏蔽notice错误
error_reporting(E_ALL ^ E_NOTICE);



//判断是否存在于黑名单中，避免重复拉黑

//获取ip
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip = '::1') {

	$ip = '127.0.0.1';

}else{

	$ip = $_SERVER['REMOTE_ADDR'];

}

$ip  = ip2long($ip);
//var_dump($ip);
//查询 ip 是否已经被拉黑
$res = select($link , DB_TABLE_BUSER,'ip',"where ip='$ip'");
//var_dump($res);
$bip = $res[0]['ip'];

if ($bip) {

	exit('该 IP 地址 已被拉入黑名单');
}

//用post接收html页面传过来的值

$username = $_POST['username'];
$revPassword = md5($_POST['password']);
$verify   = $_POST['verify'];

//判断用户是否存在，若不存在，需要注册
$result = select($link, DB_TABLE_USER,'bcount,username,password,allowlogin,loginAfter,uid,uisdel,grade',"where username='$username'");

$bcount 	= $result[0]['bcount'];
$username  	= $result[0]['username'];
$password 	= $result[0]['password'];
$allowlogin = $result[0]['allowlogin'];
$loginAfter = $result[0]['loginAfter'];
$uid		= $result[0]['uid'];
$uisdel     = $result[0]['uisdel'];
$grade0     = $result[0]['grade'];

//var_dump($username);
//var_dump($password);
//var_dump($allowlogin);
//var_dump($bcount);
//var_dump($loginAfter);
//var_dump($uid);

//查询数据库，比对用户名和密码，判断用户名与密码是否存在
if (!$username) {
	exit('用户名错误或者不存在！<a href="'.WEB_SITE.'index.php">返回登录</a>/<a href="'.WEB_SITE.'views/home/register.html">去注册</a>');
}


//判断用户是否已经被删除
if ($uisdel == 1) {
	
	exit('该用户已经被删除');
}


//判断用户是否被锁定
//再查一次

if ($allowlogin == 1 ) {

	exit('该用户已被锁定');
}


//var_dump($password);

//比对密码，判断密码是否正确
if ($revPassword !== $password) {

	//判断错误次数次时锁定用户及ip
	if ($bcount == 5){

		//修改状态，锁定用户
		$data = [
			'allowlogin'=> "1"
		];
		$res = update($link,DB_TABLE_USER, $data,"uid=$uid");
		//var_dump($res);

		//将ip拉入黑名单
		$data = [
			'ip' 		=> $ip,
			'addtime' 	=> time(),
			'overtime'  => time()+60*60*24
		];
			//var_dump($data);
		$res = insert($link,DB_TABLE_BUSER,$data);
		//var_dump($res);
		
		exit('登录已经错误5次，用户已被锁定');

	}
	//var_dump($bcount);
	$bcount  = $bcount+1;
	//var_dump($bcount);
	//若密码每错一次，修改bbs_user表，使得bcount字段值加1，并返回继续登录
	$data    = [
		'bcount'=> "$bcount"
	];

	$res 	= update($link,DB_TABLE_USER, $data,"uid=$uid");
	//var_dump($res);
		
	exit('密码已错误'.$bcount.'次');
}



//匹配验证码
//var_dump($SESSION);
if ($verify !==  $_SESSION['yzm']) {

	exit('验证码输入有误');
}

//var_dump($_SESSION);

$table = DB_TABLE_USER;
$where = "username='$username'";
$data  = ['loginAfter' => 1 , 'grade' => $grade0+30];
$res   = update($link,$table,$data,$where);
//var_dump($res);

//用session记录下用户名，及登录状态
$loginAfter = 1;		
setcookie('username',"$username",time()+60*60000,'/');
setcookie('loginAfter',"$loginAfter",time()+60*60000,'/');
setcookie('uid',"$uid",time()+60*60000,'/');

//var_dump($_COOKIE['uid']);
//var_dump($_COOKIE['username']);
//var_dump($_COOKIE['loginAfter']);
echo '登录成功,已获得30积分';

//3秒(0.0001秒哦)后自动跳转到首页
header('refresh:1;url='.WEB_SITE.'index.php');

mysqli_close($link);
